<template>
    <div>
        <div style="">
            <div
                style="position: relative;  width: 100%; height: 70%; display: flex; justify-content: center;flex-wrap: wrap; overflow-x: hidden;">
                <div style="width: 100%; height:30rem; overflow: hidden;" class="imageContainer">
                    <img :src=novel.image alt="" style="width: 100%; height: 100%; object-fit:cover;">
                </div>
                <div class="page-header">
                    <div style="flex-basis: 100%; font-size: 2rem; color: #fff;font-weight: 500;"> {{ novel.title }}
                    </div>
                    <div style="flex-basis: 100%; font-size: 1rem; color: white;">{{ novel.time }}</div>
                </div>
            </div>
            <div
                style="width:100%; height: min-content; display: flex; justify-content: center; background-color: white;">
                <v-md-preview :text="novel.content" :class="{width: isMobile }"
                    style="width: 70%; margin-top: 30px; overflow-x: hidden;" ref="articleContent"
                    @copy-code-success="handleCopyCodeSuccess(novel.content)"></v-md-preview>
                <el-card class="toc" v-if="!isMobile">
                    <div style="font-size: larger; font-weight: 600; margin-left: 100px; ">文章目录</div>

                    <el-tabs @tab-click="handleClick" v-model="activeName" :tab-position="tabPosition"
                        style="height:max-content; margin-bottom: 15px;">

                        <el-tab-pane :name="'tab' + index" :class="index == 0 ? 'current' : ''"
                            v-for="(item, index) in titles" :key="index" :label="item.title"></el-tab-pane>
                    </el-tabs>


                </el-card>

            </div>
            <div
                style="display: flex; align-items: center; justify-content: center; width: 100%; height: min-content; background-color: aliceblue; overflow: visible;">
                <el-card style="width: 90%;  margin-top: 20px; ">
                    <div slot="header"><i style="font-size: 40px; " class="el-icon-41shuoshuo"></i>
                        <span style="font-size: 30px; font-weight: bold; "> 评论</span>
                    </div>
                    <div style="display: flex; justify-content: center;">
                        <div style="width: 70%; height: auto; " class="comment">
                            <formView @load="handleLoad"></formView>
                            <div style="width: 100%; display: flex; justify-content: center; ">
                                <div style="width: 100%; margin: 20px 0 0px 0; height: auto;  ">
                                    <div
                                        style="font-size: 0.875em; margin: 0.875em 0px; font-weight: 500; font-family:Ubuntu-Bt ;">
                                        <span>{{ total }}</span> 条评论
                                    </div>
                                    <commentVue :commentList="commentList" @load="handleLoad"></commentVue>
                                </div>
                            </div>
                        </div>
                    </div>

                </el-card>
            </div>

        </div>
    </div>
</template>
<script >

import commentVue from '@/components/commentVue.vue';
/* import { Picker } from "emoji-mart-vue"; //引入组件 */
import formView from '@/components/formView.vue';

export default {

   
components:{
 commentVue,
/*  Picker, */
 formView,
},
    data() {
        return {
            total:'',
            emoji:false,
            name:'',
            email:'',
            commentList:[],
            activeName:'tab0',
            tabPosition:'right',
            scroll:'',
            titles:[],
            novel: JSON.parse(this.$route.query.novel),
            titlesDoms: [],
            isMobile: false,
            show:false,
            comment:{content:''},
            user:JSON.parse(localStorage.getItem('user' || '{}'))
        }
        
    },
    created(){
        this.getTitles();
        this.load()
    },
    mounted(){
        this.getTitles();
        /* this.setClickListen(); */
       this.checkScreenSize();
       window.addEventListener("resize", this.checkScreenSize);
       window.addEventListener('scroll', this.handleScroll);
       const buttons = document.querySelectorAll('.v-md-copy-code-btn');
    
    // 遍历这些元素并为每个元素添加点击事件监听器
    buttons.forEach(button => {
      button.addEventListener('click', this.handleCopyCodeClick);
    });
       this.show=true;
    },
  beforeDestroy() {
    window.removeEventListener("resize", this.checkScreenSize);
    window.removeEventListener('scroll', this.handleScroll);
  },

  watch:{
    scroll:function(){
        this.loadScroll();
    }
  },
  
    methods: {
        handleLoad(){
            this.load()
        },
        addEmoji(e){
            this.comment.content+=e.native
        },
        load(){
            this.$request.get('/comment',{params: {
            novelId: this.novel.id
          }}).then(res=>{
                this.commentList=res.data
            })
            this.$request.get('/comment/total',{params: {
            novelId: this.novel.id
          }}).then(res=>{
                this.total=res.data
            })
        },
        subComment(){
            this.comment.novelId=this.novel.id
                this.comment.userName=this.name
                if(this.user!=null){
                    this.comment.img = this.user.image
                    this.comment.userId = this.user.id
                    this.comment.userName = this.user.name
                }
               
            this.$request.post("comment/add",this.comment).then(res=>{
                if(res.code=='1'){
                    this.$message.success("发送成功")
                    this.load()
                }
                else
                this.$message.error(res.msg);
                
            })
        },
        handleCopyCodeClick: function handleCopyCodeClick(_ref) {
           
            var target = _ref.target;
           
            let parent = target.parentNode;
            
            var code=parent.querySelector('code').innerText;
           
                // 先给要复制的文本或者按钮加上点击事件后，并将要复制的值传过来

            if (navigator.clipboard && window.isSecureContext) {
                // navigator clipboard 向剪贴板写文本
                this.$message.success('复制成功')
                navigator.clipboard.writeText(code)
            } else {
                // 创建text area
                const textArea = document.createElement('textarea')
                textArea.value = code
                // 使text area不在viewport，同时设置不可见
                document.body.appendChild(textArea)
                textArea.focus()
                textArea.select()
                this.$message.success('复制成功')
                return new Promise((res, rej) => {
                    // 执行复制命令并移除文本框        
                    document.execCommand('copy') ? res() : rej()
                    textArea.remove()
                })
            }

            
          },

        handleClick(tab){
           
            this.$scrollTo('#header-'+tab.index, {
                        duration: 1000,
                        easing: 'ease',
                        offset: -80
                    })
        },
        loadScroll(){
            var anchors = document.querySelectorAll('h1,h2,h3,h4,h5,h6');
            
            
            for(var i=anchors.length-1;i>=0;i--){
                if(this.scroll>=anchors[i].offsetTop-100){
                   this.activeName='tab'+i
                   break;
                }
            }
        },
        handleScroll(){
           /*  let closeItem;
            let minTop=Number.POSITIVE_INFINITY;
            const anchors = this.$refs.articleContent.$el.querySelectorAll('h1,h2,h3,h4,h5,h6');
            anchors.forEach((item) => {
                const sectionPosition =  item.getBoundingClientRect()
                if (sectionPosition.top >= 0 && sectionPosition.top <= minTop){
                    minTop=sectionPosition.top;
                    closeItem=item;
                }
            })
            document.querySelectorAll('a.highlight')
                .forEach(a => a.classList.remove('highlight'));
                document.querySelector('.'+closeItem.id).classList.add('highlight') */
           this.scroll=document.documentElement.scrollTop||document.body.scrollTop;
        },
        checkScreenSize() {
            this.isMobile = window.innerWidth <= 768;
        },
        handleCopyCodeSuccess(code) {
            console.log(code);
        },
        getTitles() {
            // 文章目录操作
            const anchors = document.querySelectorAll('h1,h2,h3,h4,h5,h6');
            // 给h1，2，3标签设置id
            anchors.forEach((item, index) => {
                item.setAttribute('id', 'header-' + index)
            })
            // 存数组，后续监听该标题的变化位置来高亮标题
            this.titlesDoms = anchors

            // 判断标题里是否为空
            const titles = Array.from(anchors).filter((title) => title.innerText.trim() !== null);
            if (!titles.length) {
                this.titles = [];
                return;
            }

            const hTags = Array.from(new Set(titles.map((title) => title.tagName))).sort();
            this.titles = titles.map((el, index) => ({
                id: 'header-' + index,
                title: el.innerText,
                // lineIndex: el.getAttribute('data-v-md-line'),
                level: Number(el.nodeName.substring(1, 2)),
                indent: hTags.indexOf(el.tagName),
            }));    
          /*   setTimeout(() => {
                this.setClickListen()
                // 初始化高亮
            }, 50) */
        },
    /* setClickListen() {
        const headers = document.querySelectorAll('a');
        console.log(headers)
        headers.forEach(header => {

            if (header.id.startsWith('header')) {
                
                header.addEventListener('click', () => {
                    this.$scrollTo('#'+header.className, {
                        duration: 1000,
                        easing: 'ease',
                        offset: -80
                    })
                    this.highlight(header)
                })
            }
        })
    },
        highlight(header) {
            // 清空所有a标签的高亮,进行初始化
            document.querySelectorAll('a.highlight')
                .forEach(a => a.classList.remove('highlight'));
            //将此次点击的header目录进行添加高亮
            console.log(header.className);
            if (document.querySelector('.'+header.className) == null) {
                console.log('空')
                return
            }
            console.log(document.querySelector(`a#${header.id}`))
            document.querySelector('.'+header.className).classList.add('highlight')
        } */


}


}
</script>
<style >
@media (max-width:768px) {
    .comment{
        width: 95% !important;
    }    
}

.imageContainer{
    animation: header 1s ease ;
}

.imageContainer::before{
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color:#0000004d;
    z-index: 1;

}
.page-header{
    z-index: 1;
    bottom: 2em;
    margin-top: 0;
    position: absolute;
    text-shadow: 2px 2px 10px #000;
    width: 780px;
}
.el-tabs--right .el-tabs__header.is-right{
    margin-right: 80px !important;
}

.highlight{
    color: aqua;
    font-size: large;
}

.el-tabs__content{
    width: 0 !important;
}

.toc {
    width: 300px;
    margin-top: 100px;
    margin-left: 50px ;
    height:min-content;
    display: flex;
    
    position: sticky ;
    top:60px ; 
    left: 0 ;
}

.toc a {
    text-decoration:none;
    font-size: medium;
    color:black;
    
}


.toc li{
    list-style-type: none;
 
}

.toc a.highlight {
  /* 高亮链接样式 */

  color: red; /* 例如，将文字颜色设置为红色 */
}
.width{
    width: 90% !important;
}

.emoji-mart{
    z-index: 100 !important;
}
@keyframes header{
  0%{
    opacity: 0;
    transform: translateY(-50px);
  } 
  100%{
    opacity: 1;
    transform: translateY(0);
  }
  
}
@keyframes fadeInUp {
    0% {
        opacity: 0;
        transform: translate3d(0px, 5%, 0px);
    }

    100% {
        opacity: 1;
        transform: translate3d(0px, 0px, 0px);
    }
}

@media (max-width: 768px) {
    .imageContainer {
        height: 17.5rem !important;
    }
    .page-header{
        width: 100% !important;
        text-align: center;
    }
}
</style>
